package com.ug_project.spring_dict.Controllers

import com.ug_project.spring_dict.DataAccess.Migrations.DictTables.*
import com.ug_project.spring_dict.DataAccess.connectDb
import com.ug_project.spring_dict.WebApiV1
import com.ug_project.spring_dict.WebApiV1_1
import com.ug_project.spring_dict.com.ug_project.spring_dict.DataAccess.SearchRepository
import com.ug_project.spring_dict.com.ug_project.spring_dict.Entities.SearchResult
import com.ug_project.spring_dict.com.ug_project.spring_dict.Entities.WordItem
import io.ktor.application.Application
import io.ktor.locations.Location
import io.ktor.locations.get
import io.ktor.locations.location
import io.ktor.response.respond
import io.ktor.routing.get
import io.ktor.routing.routing
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.transaction


fun Application.searchModule() {

    routing {

        @Location("Search")
        data class SearchModel(var keyWord: String, var from: String = "EnUg", var searchMode: String = "startsWith", var pageIndex: Int = 0, var count: Int = 50)


        location(WebApiV1::class) {


            get<SearchModel> {
//                val repo = SearchRepository()
//
//                context.respond(repo.search(it.keyWord, it.from, it.searchMode, it.pageIndex, it.count))
                context.respond(SearchResult(listOf(
                        WordItem("ئۇقتۇرۇش", "مۇلازىمەت تەمىنلەش توختىتىلدى، ئىشلەتكىنىڭىزگە رەھمەت \n Providing search service has stopped, thank you for using. \n提供搜索服务已停止， 谢谢使用", 0)
                ), "en-ug"))
            }

            data class DictDirection(var source: String, var sourceRtl: Boolean, var destination: String, var destinationRtl: Boolean, var code: String)
            get {

                val directions = transaction(connectDb()) {
                    Dictionaries.select { Dictionaries.enabled eq true }.adjustSlice { slice(Dictionaries.sourceLanguageLabel, Dictionaries.sourceLanguageDirectionIsRtl, Dictionaries.destinationLanguageLabel, Dictionaries.destinationLanguageDirectionIsRtl, Dictionaries.languagesCode) }.map {
                        DictDirection(
                                it[Dictionaries.sourceLanguageLabel],
                                it[Dictionaries.sourceLanguageDirectionIsRtl],
                                it[Dictionaries.destinationLanguageLabel],
                                it[Dictionaries.destinationLanguageDirectionIsRtl],
                                it[Dictionaries.languagesCode]
                        )
                    }
                }
                context.respond(directions)
            }
        }

        location(WebApiV1_1::class) {

            get<SearchModel> {
                val repo = SearchRepository()

                context.respond(repo.search(it.keyWord, it.from, it.searchMode, it.pageIndex, it.count))
            }
        }
    }
}
